import { Request, Response } from 'express';
import { CartModel } from '../models/Cart';
import { asyncHandler } from '../utils/asyncHandler';
import { ApiResponse } from '../types';
import { CartRequest, UpdateCartRequest } from '../types/order';

// Express类型扩展
declare global {
  namespace Express {
    interface Request {
      user?: {
        id: number;
        username: string;
        email: string;
        role?: string;
        [key: string]: any;
      };
    }
  }
}

// 获取购物车列表
export const getCartItems = asyncHandler(async (req: Request, res: Response) => {
  const userId = req.user?.id;

  if (!userId) {
    const response: ApiResponse = {
      code: 401,
      message: '用户未登录'
    };
    return res.status(401).json(response);
  }

  const cartItems = await CartModel.findByUserId(userId);

  const response: ApiResponse = {
    code: 200,
    message: '获取购物车成功',
    data: cartItems
  };

  res.json(response);
});

// 添加商品到购物车
export const addToCart = asyncHandler(async (req: Request, res: Response) => {
  const userId = req.user?.id;
  const cartData: CartRequest = req.body;

  if (!userId) {
    const response: ApiResponse = {
      code: 401,
      message: '用户未登录'
    };
    return res.status(401).json(response);
  }

  // 验证必填字段
  if (!cartData.productId || !cartData.quantity || cartData.quantity <= 0) {
    const response: ApiResponse = {
      code: 400,
      message: '缺少必填字段或数量无效'
    };
    return res.status(400).json(response);
  }

  try {
    const cartItemId = await CartModel.addItem(userId, cartData);

    const response: ApiResponse = {
      code: 200,
      message: '添加到购物车成功',
      data: { cartItemId }
    };

    res.json(response);
  } catch (error: any) {
    const response: ApiResponse = {
      code: 400,
      message: error.message || '添加到购物车失败'
    };
    res.status(400).json(response);
  }
});

// 更新购物车项
export const updateCartItem = asyncHandler(async (req: Request, res: Response) => {
  const userId = req.user?.id;
  const { id } = req.params;
  const updateData: UpdateCartRequest = req.body;
  const cartItemId = parseInt(id);

  if (!userId) {
    const response: ApiResponse = {
      code: 401,
      message: '用户未登录'
    };
    return res.status(401).json(response);
  }

  if (isNaN(cartItemId)) {
    const response: ApiResponse = {
      code: 400,
      message: '无效的购物车项ID'
    };
    return res.status(400).json(response);
  }

  // 验证数量
  if (updateData.quantity !== undefined && updateData.quantity <= 0) {
    const response: ApiResponse = {
      code: 400,
      message: '数量必须大于0'
    };
    return res.status(400).json(response);
  }

  const success = await CartModel.updateItem(cartItemId, userId, updateData);

  if (!success) {
    const response: ApiResponse = {
      code: 404,
      message: '购物车项不存在或更新失败'
    };
    return res.status(404).json(response);
  }

  const response: ApiResponse = {
    code: 200,
    message: '更新购物车成功'
  };

  res.json(response);
});

// 删除购物车项
export const deleteCartItem = asyncHandler(async (req: Request, res: Response) => {
  const userId = req.user?.id;
  const { id } = req.params;
  const cartItemId = parseInt(id);

  if (!userId) {
    const response: ApiResponse = {
      code: 401,
      message: '用户未登录'
    };
    return res.status(401).json(response);
  }

  if (isNaN(cartItemId)) {
    const response: ApiResponse = {
      code: 400,
      message: '无效的购物车项ID'
    };
    return res.status(400).json(response);
  }

  const success = await CartModel.deleteItem(cartItemId, userId);

  if (!success) {
    const response: ApiResponse = {
      code: 404,
      message: '购物车项不存在或删除失败'
    };
    return res.status(404).json(response);
  }

  const response: ApiResponse = {
    code: 200,
    message: '删除购物车项成功'
  };

  res.json(response);
});

// 批量删除购物车项
export const deleteCartItems = asyncHandler(async (req: Request, res: Response) => {
  const userId = req.user?.id;
  const { ids } = req.body;

  if (!userId) {
    const response: ApiResponse = {
      code: 401,
      message: '用户未登录'
    };
    return res.status(401).json(response);
  }

  if (!Array.isArray(ids) || ids.length === 0) {
    const response: ApiResponse = {
      code: 400,
      message: '请提供要删除的购物车项ID列表'
    };
    return res.status(400).json(response);
  }

  const success = await CartModel.deleteItems(ids, userId);

  if (!success) {
    const response: ApiResponse = {
      code: 400,
      message: '删除购物车项失败'
    };
    return res.status(400).json(response);
  }

  const response: ApiResponse = {
    code: 200,
    message: '批量删除购物车项成功'
  };

  res.json(response);
});

// 清空购物车
export const clearCart = asyncHandler(async (req: Request, res: Response) => {
  const userId = req.user?.id;

  if (!userId) {
    const response: ApiResponse = {
      code: 401,
      message: '用户未登录'
    };
    return res.status(401).json(response);
  }

  const success = await CartModel.clearCart(userId);

  const response: ApiResponse = {
    code: 200,
    message: '清空购物车成功'
  };

  res.json(response);
});

// 获取选中的购物车项
export const getSelectedCartItems = asyncHandler(async (req: Request, res: Response) => {
  const userId = req.user?.id;

  if (!userId) {
    const response: ApiResponse = {
      code: 401,
      message: '用户未登录'
    };
    return res.status(401).json(response);
  }

  const cartItems = await CartModel.getSelectedItems(userId);

  const response: ApiResponse = {
    code: 200,
    message: '获取选中购物车项成功',
    data: cartItems
  };

  res.json(response);
});

// 全选/取消全选
export const selectAllCartItems = asyncHandler(async (req: Request, res: Response) => {
  const userId = req.user?.id;
  const { selected } = req.body;

  if (!userId) {
    const response: ApiResponse = {
      code: 401,
      message: '用户未登录'
    };
    return res.status(401).json(response);
  }

  if (typeof selected !== 'boolean') {
    const response: ApiResponse = {
      code: 400,
      message: '请提供有效的选中状态'
    };
    return res.status(400).json(response);
  }

  const success = await CartModel.selectAll(userId, selected);

  const response: ApiResponse = {
    code: 200,
    message: selected ? '全选成功' : '取消全选成功'
  };

  res.json(response);
});

// 获取购物车统计
export const getCartStats = asyncHandler(async (req: Request, res: Response) => {
  const userId = req.user?.id;

  if (!userId) {
    const response: ApiResponse = {
      code: 401,
      message: '用户未登录'
    };
    return res.status(401).json(response);
  }

  const stats = await CartModel.getCartStats(userId);

  const response: ApiResponse = {
    code: 200,
    message: '获取购物车统计成功',
    data: stats
  };

  res.json(response);
});